package logic

import (
	"context"
	"fmt"
	"goods/goodsrpc/goodsrpc"
	"goods/goodsrpc/internal/svc"
	"goods/models/mysql"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsAddLogic {
	return &GoodsAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodsAddLogic) GoodsAdd(in *goodsrpc.GoodsAddRequest) (*goodsrpc.GoodsAddResponse, error) {
	// todo: add your logic here and delete this line

	var class mysql.Class
	mysql.DB.Debug().Where("id=?", in.ClassId).Find(&class)
	if class.ID == 0 {
		return nil, fmt.Errorf("找不到该分类")
	}

	goods := mysql.Goods{
		Title:   in.Title,
		ClassId: in.ClassId,
		Price:   float64(in.Price),
		Info:    in.Info,
		UserId:  in.UserId,
	}
	mysql.DB.Debug().Create(&goods)

	class.GoodNum = class.GoodNum + 1
	mysql.DB.Debug().Updates(&class)
	return &goodsrpc.GoodsAddResponse{
		GoodsId: int64(goods.ID),
	}, nil
}
